﻿using System;
using System.Web.Mvc;
using System.Text;
using System.Collections.Generic;
using System.Web.Routing;

namespace TSites.Administrator.Extensions
{
	public static class HtmlHelperExtension
	{
		public static MvcHtmlString DatePicker(this HtmlHelper helper, string name, object date, object datetimePickerAttr)
		{
			StringBuilder html = new StringBuilder(512);

			// Build our base input element
			html.Append("<input type=\"text\" id=\"").Append(name)
				.Append("\" name=\"").Append(name).Append("\"");

			// Model Binding Support
			if (date != null)
			{
				string dateValue = String.Empty;
				if (date != null)
				{
					if (date is string)
					{
						dateValue = date.ToString();
					}
					else
					{
						DateTime dateTmp = (DateTime)date;
						if (dateTmp != DateTime.MinValue)
						{
							dateValue = dateTmp.ToString();
						}
					}
				}

				html.Append(" value=\"").Append(dateValue).Append("\"");
			}

			// We're hard-coding the width here, a better option would be to pass in html attributes and reflect through them
			// here ( default to 75px width if no style attributes )
			html.Append(" readonly />");

			// Now we call the datepicker function, passing in our options.  Again, a future enhancement would be to
			// pass in date options as a list of attributes ( min dates, day/month/year formats, etc. )
			html.Append(BuildDatetimePicker(name, new RouteValueDictionary(datetimePickerAttr)));

			return MvcHtmlString.Create(html.ToString());
		}

		public static string BuildDatetimePicker(string name, IDictionary<string, object> datetimePickerAttr)
		{
			object value;
			StringBuilder datetimePickerBuilder = new StringBuilder(512);
			datetimePickerBuilder.Append("<script type=\"text/javascript\">$(document).ready(function() { $('#")
				.Append(name).Append("').datepicker({ ");
			// date format
			if (datetimePickerAttr.TryGetValue("dateFormat", out value))
			{
				datetimePickerBuilder.Append("dateFormat: '").Append(value.ToString()).Append("'");
			}
			// display Month, Year
			if (datetimePickerAttr.TryGetValue("displayMonYear", out value))
			{
				datetimePickerBuilder.Append(", changeMonth: ").Append(value.ToString().ToLower())
					.Append(", changeYear: ").Append(value.ToString().ToLower());
			}
			// Year range
			if (datetimePickerAttr.TryGetValue("yearRange", out value))
			{
				datetimePickerBuilder.Append(", yearRange: '").Append(value.ToString()).Append("'");
			}
			datetimePickerBuilder.Append(", duration: 0 }");
			// regional
			if (datetimePickerAttr.TryGetValue("regional", out value))
			{
				datetimePickerBuilder.Append(", $.datepicker.regional['").Append(value).Append("']");
			}
			datetimePickerBuilder.Append("); });</script>");

			return datetimePickerBuilder.ToString();
		}
	}
}